<!-- 功能  系统升级弹窗 | 作者：menghao.yan | 邮箱：yxs2615@163.com | 时间：2023年08月24日 14:23:00 -->
<template>
  <!-- 弹出框 -->
  <a-modal v-model:open="visible" title="系统升级" width="500px" class="y-modal" okText="创建" @ok="onSubmit" @cancel="onCancel">
    <a-form :label-col="{ span:6 }" :wrapper-col="{span: 14}">
      <a-form-item label="控制器" v-bind="validateInfos.controller">
        <a-select v-model:value="modelRef.controller" placeholder="请选择控制器">
          <a-select-option value="controller-1">controller-1</a-select-option>
          <a-select-option value="controller-2">controller-2</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="选择文件" v-bind="validateInfos.fileList">
        <a-row :gutter="12">
          <a-col flex="20px">
            <a-upload v-model:fileList="modelRef.fileList" :before-upload="beforeUpload" @remove="handleRemove">
              <a-button>
                <upload-outlined></upload-outlined>
                选择文件
              </a-button>
            </a-upload>
          </a-col>
          <a-col flex="20px">
            <a-button type="primary" :disabled="modelRef.fileList.length === 0" @click="handleUpload" class="y-btn">
              开始上传
            </a-button>
          </a-col>
        </a-row>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const { visible } = toRefs(props)

// 定义组件的事件
const emits = defineEmits(['update:visible'])

import { Form } from 'ant-design-vue'

const useForm = Form.useForm

const modelRef = reactive({
  controller: 'controller-1',
  fileList: []
})

const rulesRef = reactive({
  controller: [
    {
      required: true,
      message: '请选择控制器'
    }
  ],
  fileList: [
    {
      required: true,
      validator: async (_rule, value) => {
        if (value.length == 0) {
          return Promise.reject('请上传文件!')
        }
        return Promise.resolve()
      },
      trigger: ['change', 'blur']
    }
  ]
})

const { resetFields, validate, validateInfos, mergeValidateInfo } = useForm(modelRef, rulesRef)
const onSubmit = () => {
  validate()
    .then(() => {
      console.log('系统升级>>', toRaw(modelRef))
      onCancel()
    })
    .catch(err => {
      console.log('error', err)
    })
}

const onCancel = () => {
  // 触发自定义事件来通知父组件关闭弹窗
  emits('update:visible', false)
}

const handleRemove = file => {
  const index = modelRef.fileList.indexOf(file)
  const newFileList = modelRef.fileList.slice()
  newFileList.splice(index, 1)
  modelRef.fileList = modelRef.fileList
}
const beforeUpload = file => {
  modelRef.fileList = [...(modelRef.fileList || []), file]
  return false
}
const handleUpload = () => {}
</script>

<style scoped>
.ant-row {
  margin-bottom: 10px;
}
</style>